package com.horay.springbootdemo.environment.multiple;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 服务启动类
 *
 * @author heyingcheng
 * @date 2019/10/31 21:29
 */
@Slf4j
@SpringBootApplication
public class EnvironmentMultipleApplcation extends SpringBootServletInitializer implements CommandLineRunner {

    /**
     * 服务器配置文件类型
     */
    private static final List<String> DEPLOY_ENV = Arrays.asList("develop", "test", "product");

    @Value("${spring.profiles.active}")
    private String profilesActive;
    @Value("${spring.boot.demo.config.value}")
    private String configValue;

    /**
     * 通过应用服务器容器托管的服务器入口，使用profiles方法来决定加载那一个配置文件
     *
     * @param application
     * @return org.springframework.boot.builder.SpringApplicationBuilder
     * @author heyingcheng
     * @date 2019/11/17 16:54
     */
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(EnvironmentMultipleApplcation.class).profiles(getProfile());
    }

    /**
     * 动态指定spring.profiles.active
     * java -jar -Dspring.profiles.active=product
     *
     * @param args
     * @author heyingcheng
     * @date 2019/11/17 17:08
     * @return void
     */
    public static void main(String[] args) {
//        new SpringApplicationBuilder().sources(EnvironmentMultipleApplcation.class).profiles(getProfile()).run(args);
        SpringApplication.run(EnvironmentMultipleApplcation.class, args);
    }

    /**
     * 获取设置的系统环境变量，然后决定加载那一个配置文件
     *
     * @param
     * @author heyingcheng
     * @date 2019/11/17 16:56
     * @return java.lang.String
     */
    private static final String getProfile() {
        Map<String, String> environment = System.getenv();
        String env = environment.get("PROFILE_OF_ENV");
        String profile = (env != null && DEPLOY_ENV.contains(env) ? env : "develop");
        return profile;
    }

    @Override
    public void run(String... args) throws Exception {
        log.info("profilesActive:[{}], configValue:[{}]", profilesActive, configValue);
    }

}
